package com.wang.mall.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class RabbitMQConfig {


    /**
     * 使用json序列化机制,进行消息转换
     *
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }


    /**
     * 创建库存交换机 wang-stock-event-exchange
     *
     * @return
     */
    @Bean
    public Exchange wangStockEventExchange() {
        return new TopicExchange(
                "wang-stock-event-exchange",
                true, false
        );
    }


    /**
     * 如果wang-stock-delay-queue 队列里面的
     * 消息没有被确认,消息就会进入这个队列里面
     * <p>
     * 创建 wang-stock-release-queue ,
     * 这里面存储的是,没有被确认支付的订单的信息
     *
     * @return
     */
    @Bean
    public Queue wangStockReleaseStock() {
        return new Queue("wang-stock-release-queue",
                true, false, false);
    }


    /**
     * 订单创建完毕, 发送消息到这个队列,
     * 这是个死信队列,消息有延迟时间,
     * 在延迟时间到达后,才会把消息发送给消费者,
     * 如果消息没有被消费者确认,
     * 则进入死信状态, 就把消息发送给 wang-stock-event-exchange
     * <p>
     * wang-stock-delay-queue
     *
     * @return
     */
    @Bean
    public Queue wangStockDelay() {
        HashMap<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", "wang-stock-event-exchange"); // 消息过期后被丢到那个交换机里边
        arguments.put("x-dead-letter-routing-key", "stock.release"); // 路由键
        arguments.put("x-message-ttl", 120000); // 消息过期时间 1分钟
        return new Queue("wang-stock-delay-queue",
                true, false, false, arguments);

    }


    /**
     * 创建
     * wang-stock-event-exchange 和 wang-stock-release-queue
     * 的绑定关系
     * <p>
     * 路由键 stock.release.#
     *
     * @return
     */
    @Bean
    public Binding stockLocked() {
        return new Binding("wang-stock-release-queue",
                Binding.DestinationType.QUEUE,
                "wang-stock-event-exchange",
                "stock.release.#", null);
    }


    /**
     * 创建
     * wang-stock-event-exchange 和 wang-stock-delay-queue
     * 的绑定关系
     * <p>
     * 路由键 stock.locked
     *
     * @return
     */
    @Bean
    public Binding stockDelay() {
        return new Binding("wang-stock-delay-queue",
                Binding.DestinationType.QUEUE,
                "wang-stock-event-exchange",
                "stock.locked", null);
    }


}
